import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { Affix, Button, Input, Modal, notification, Space, Tag } from "antd"
import { Link } from "react-router-dom"
import { addTagId, clearTag, removeTag, tags as tagsRedux } from '@/store/tags';
import { main } from '@model';
import { useEffect, useState } from 'react';
import { DeleteTag, TagList, UpdateTag } from '@app';
import RightMenu from '@right-menu/react'
import { DogInTheManger } from '@/config/TitleBarHiddenInset';
import { setPageNumber } from '@/store/pageNumber';

export default function SiderMenu() {
  const dispatch = useAppDispatch()
  const selectedTags = useAppSelector(tagsRedux)

  const [tags, setTags] = useState(Array<main.Tag>())

  // operation tag
  const [operationTag, setOperationTag] = useState<main.Tag | null>(null)
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    fetchTag()
  }, [])

  const fetchTag = () => {
    TagList().then(tags => {
      setTags(tags)
    })
  }

  const selectTag = (tag: main.Tag) => {
    if (selectedTags.indexOf(tag.id) == -1) {
      dispatch(addTagId(tag.id))
    } else {
      dispatch(removeTag(tag.id))
    }
    dispatch(setPageNumber(1))
  }

  const deleteTag = (tag: main.Tag) => {
    DeleteTag(tag.id).then(() => {
      dispatch(removeTag(tag.id))
      fetchTag()
    }).catch(err => {
      notification.error({
        message: '删除失败！',
        description: err,
        placement: 'bottomLeft',
      })
    })
  }

  const updateTag = async () => {
    if (operationTag) {
      await UpdateTag(operationTag).catch(err => {
        notification.error({
          message: '更新失败！',
          description: err,
          placement: 'bottomLeft',
        })
      }).finally(() => {
        setOperationTag(null)
      })
    }

    fetchTag()
  }

  return <Affix offsetTop={10}>
    <div>
      <Space>
        <DogInTheManger />
        <Link to='/note'><Button type="primary">添加</Button></Link>
      </Space>
      <div><br /></div>
      <Space wrap>
        {tags.map(tag => (
          <RightMenu key={tag.id} options={[
            {
              type: 'li',
              text: '重命名',
              callback: () => {
                setOperationTag(tag)
                setVisible(true)
              }
            },
            {
              type: 'li',
              text: '删除',
              callback: () => {
                deleteTag(tag)
              }
            },
          ]} theme={'win10'} minWidth={'100px'} maxWidth={'200px'} onBeforeInit={() => { }} onAfterInit={() => { }}>
            <Tag
              style={
                selectedTags.indexOf(tag.id) != -1 ? {
                  borderColor: '#1677ff',
                  cursor: 'pointer',
                } : {
                  cursor: 'pointer',
                }
              }
              onClick={() => selectTag(tag)}>
              {tag.name}
            </Tag>
          </RightMenu>
        ))}
      </Space>
      <div><br /></div>
      {selectedTags.length > 0 && (
        <Button type='primary' danger size='small' onClick={() => { dispatch(clearTag()) }}>清除</Button>
      )}

      {/* rename tag modal */}
      <Modal open={visible}
        onOk={async () => {
          await updateTag()
          setVisible(false)
        }}
        cancelText={'取消'}
        okText={'确认'}
        onCancel={() => { setVisible(false) }}
        closeIcon={false}>

        <Input
          defaultValue={operationTag?.name}
          key={operationTag?.name}
          onChange={(e) => {
            if (operationTag) {
              operationTag.name = e.target.value
            }
          }} />
      </Modal>
    </div>
  </Affix>
}
